/*
 * Communicates with the server and sends location updates to stalkernetmanager.
 */
package com.stalkernet;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.widget.Toast;


public class StalkernetService extends Service {

	private NotificationManager mNotificationManager;
	private int SERVICE_RUNNING = 0;

	
	private LocationManager locationManager;
	private StalkernetLocationListener mLocListener;
	
	
	public final static String broadcastIntentString="broadcastLocation"; 
	public final static String friendBroadcast="friendBroadcast"; 

	void startMonitoring()
	{
		
		Notification notification = new Notification(R.drawable.icon2, "Cnvrging!", System.currentTimeMillis());
		mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

		CharSequence contentTitle = "CNVR.GE";
		CharSequence contentText = "Find yo' kids, find yo' wife!";
		Intent notificationIntent = new Intent(this, StalkernetManager.class);
		PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

		notification.flags |= Notification.FLAG_ONGOING_EVENT;
		notification.setLatestEventInfo(getApplicationContext(), contentTitle, contentText, contentIntent);
		mNotificationManager.notify(SERVICE_RUNNING, notification);

		locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		mLocListener = new StalkernetLocationListener();
		locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, mLocListener);
						
//		StalkernetBase.t(this, "requesting location updates");
		

	}
	void stopMonitoring()
	{
		mNotificationManager.cancel(SERVICE_RUNNING);
		locationManager.removeUpdates(mLocListener);
	}
	
	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	@Override
	public void onCreate() {
		
		super.onCreate();

		StalkernetBase.d("\t\t\t\tservice","onCreate");
		//StalkernetBase.t(this, "StalkernetService Started");
				
		startMonitoring();
		//this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
	
	}
	
	@Override
	public void onDestroy() {
		// TODO Auto-generated method stub
		Toast.makeText(this, "GEService destroyed", Toast.LENGTH_SHORT);
		stopMonitoring();
		super.onDestroy();
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
	
		return START_STICKY;
	}
	
	
	/*
	 * THIS IS HACKY
	 * TODO: remove this shit
	 */
	public static void testUpdateLocation(Context c, int userid, double lat,
			double lng) {
		String urlString = "http://astar.xvm.mit.edu/updateLocation/";
		// "userid/lat/lng"; // latlng=40.714224,-73.961452&sensor=true;
		urlString += userid;
		urlString += "/";
		urlString += lat;
		urlString += "/";
		urlString += lng;

		StringBuilder response = new StringBuilder();
		StalkernetBase.d("updatelocation", "url is:" + urlString);
		//StalkernetBase.t(c, "url is:" + urlString);
		URL url = null;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		HttpURLConnection httpconn;

		try {
			httpconn = (HttpURLConnection) url.openConnection();

			if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader input = new BufferedReader(
						new InputStreamReader(httpconn.getInputStream()), 8192);
				String strLine = null;
				while ((strLine = input.readLine()) != null) {
					response.append(strLine);
				}
				input.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// return response.toString();
	}

	public void updateLocation(int userid, double lat, double lng) {
		String urlString = "http://astar.xvm.mit.edu/updateLocation/";
		// "userid/lat/lng"; // latlng=40.714224,-73.961452&sensor=true;
		urlString += userid;
		urlString += "/";
		urlString += lat;
		urlString += "/";
		urlString += lng;

		StringBuilder response = new StringBuilder();
		StalkernetBase.d("updatelocation", "url is:" + urlString);
		//StalkernetBase.t(this, "url is:" + urlString);
		URL url = null;
		try {
			url = new URL(urlString);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

		HttpURLConnection httpconn;

		try {
			httpconn = (HttpURLConnection) url.openConnection();

			if (httpconn.getResponseCode() == HttpURLConnection.HTTP_OK) {
				BufferedReader input = new BufferedReader(
						new InputStreamReader(httpconn.getInputStream()), 8192);
				String strLine = null;
				while ((strLine = input.readLine()) != null) {
					response.append(strLine);
				}
				input.close();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// return response.toString();
	}

	class StalkernetLocationListener implements LocationListener
	{

		@Override
		public void onLocationChanged(Location loc) {
			Intent intent=new Intent(broadcastIntentString);
			intent.putExtra("myLoc", loc);
			
			//sendBroadcast(intent);
			//StalkernetBase.t(StalkernetService.this, "onLocationChange!"+loc.getLatitude() + "\t"+loc.getLongitude());
			StalkernetBase.d("onLocationChange!"+loc.getLatitude() + "\t"+loc.getLongitude());
			updateLocation(Stalkernet.getUserid(), loc.getLatitude(), loc.getLongitude());		
			
		}

		@Override
		public void onProviderDisabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onProviderEnabled(String arg0) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
			// TODO Auto-generated method stub
			
		}
		
	}
}
